﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Collections;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System.Diagnostics;
using System.Device;
using System.IO;
using System.Text;
using Microsoft.Phone.Shell;

namespace unifiqAnthony
{
    public partial class Planner : PhoneApplicationPage
    {
        private static string API_KEY = "AoetA0820tVc4COdo9bGyEKy0mBSDjoSeb9vlIRP3iC3RWibRFlwOGPGVLOUn7Fs";
        private List<RequestData> requestDataList = new List<RequestData>();
        private string lat, lng, desc, title, date, time;
        private int groupID, creatorID;

        public Planner()
        {
            InitializeComponent();

            //date_picker.Value = DateTime.Now.Date;
            //time_picker.Value = DateTime.Now;

            User user = (User)PhoneApplicationService.Current.State["currentUser"];
            creatorID = user.uid;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            groupID = Convert.ToInt32(NavigationContext.QueryString["groupID"]);
            PageTitle.Text = NavigationContext.QueryString["groupName"];
        }

        private void submit_btn_Click(object sender, RoutedEventArgs e)
        {
            bool valid = true;
            if (title_tb.Text.Equals("Enter event title"))
            {
                MessageBox.Show("Please enter an event title", "Event title field required", MessageBoxButton.OK);
                valid = false;
            }
            else if (location_lp.Items.Count <= 0)
            {
                MessageBox.Show("Please enter an event location", "Event location field required", MessageBoxButton.OK);
                valid = false;
            }
            else if (date_picker.Value.Value.Date.CompareTo(DateTime.Now.Date) < 0)
            {
                MessageBox.Show("Please enter a valid event date", "Event date has passed", MessageBoxButton.OK);
                valid = false;
            }
            else if (time_picker.Value.Equals(""))
            {
                MessageBox.Show("Please enter an event time", "Event time field required", MessageBoxButton.OK);
                valid = false;
            }

            if (valid && comment_tb.Text.Equals("Enter event description"))
            {
                if (MessageBox.Show("You have not entered a description. Submit anyway?", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    valid = false;
                }
                else
                {
                    comment_tb.Text = "";
                }
            }


            if (valid)
            {
                RequestData requestData = requestDataList[location_lp.SelectedIndex];
                lat = requestData.latitude;
                lng = requestData.longitude;
                title = title_tb.Text;
                desc = comment_tb.Text;

                string[] tempDateArr = date_picker.Value.ToString().Split('/');
                date = tempDateArr[2].Substring(0, 4) + "-" + tempDateArr[0] + "-" + tempDateArr[1];
                string[] tempTimeArr = time_picker.Value.ToString().Split(' ');
                if (tempTimeArr[2].Equals("PM"))
                {
                    time = (12 + Convert.ToInt32(tempTimeArr[1].Split(':')[0])).ToString() + ":" + tempTimeArr[1].Split(':')[1] + ":" + tempTimeArr[1].Split(':')[2];
                }
                else
                {
                    time = tempTimeArr[1];
                }

                var url = "http://unifiq.5kportal.com/create_bing_event.php";

             
             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
             webRequest.Method = "POST";
             webRequest.ContentType = "application/x-www-form-urlencoded";

             webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
             MessageBox.Show("Event successfully created!");
             title_tb.Text = "Enter event title";
             location_autocomplete.Text = "";
             location_lp.Items.Clear();
             comment_tb.Text = "Enter event description";


            }
        }

         void GetRequestStreamCallback(IAsyncResult asynchronousResult)
         {
             HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
             // End the stream request operation
             Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);

             // Create the post data
             // Demo POST data 
             string postData = "creatorID=" + creatorID.ToString() + "&name=" + title + "&dateTime=" + date + "%20" + time + "&groupID=" + groupID.ToString() + "&latitude=" + lat + "&longitude=" + lng + "&description=" + desc;
             Debug.WriteLine(postData);
             byte[] byteArray = Encoding.UTF8.GetBytes(postData);

             // Add the post data to the web request
             postStream.Write(byteArray, 0, byteArray.Length);
             postStream.Close();

             // Start the web request
             webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
         }

         void GetResponseCallback(IAsyncResult asynchronousResult)
         {
             try
             {
                 HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                 HttpWebResponse response;

                 // End the get response operation
                 response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                 Stream streamResponse = response.GetResponseStream();
                 StreamReader streamReader = new StreamReader(streamResponse);
                 var Response = streamReader.ReadToEnd();
                 streamResponse.Close();
                 streamReader.Close();
                 response.Close();

             }
             catch (WebException e)
             {
                 MessageBox.Show(e.ToString());
             }
         }

        private void comment_tb_MouseEnter(object sender, MouseEventArgs e)
        {
            if (comment_tb.Text.Equals("Enter event description"))
            {
                comment_tb.Text = "";
            }
        }

        private void comment_tb_MouseLeave(object sender, MouseEventArgs e)
        {
            if (comment_tb.Text.Equals(""))
            {
                comment_tb.Text = "Enter event description";
            }
        }

        private void title_tb_MouseEnter(object sender, MouseEventArgs e)
        {
            if (title_tb.Text.Equals("Enter event title"))
            {
                title_tb.Text = "";
            }
        }

        private void title_tb_MouseLeave(object sender, MouseEventArgs e)
        {
            if (title_tb.Text.Equals(""))
            {
                title_tb.Text = "Enter event title";
            }
        }


        private void location_autocomplete_TextChanged(object sender, RoutedEventArgs e)
        {
            location_lp.Items.Clear();
            string loadingMsg = "Loading locations...";
            location_lp.Items.Add(loadingMsg);
            string locationURL = "https://dev.virtualearth.net/REST/v1/Locations?q=" + location_autocomplete.Text + "&maxResults=10&key=" + API_KEY;
            var autoCompleteClient = new RestClient(locationURL);
            var locationRequest = new RestRequest();
            locationRequest.Method = Method.GET;
            locationRequest.RequestFormat = DataFormat.Json;
            List<string> dataSource = new List<string>();
            autoCompleteClient.ExecuteAsync(locationRequest, response =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    requestDataList.Clear();
                    var json = response.Content;
                    var jsonObject = JObject.Parse(json);
                    var dict = JsonConvert.DeserializeObject<RootObject>(json);
                    var resources = dict.resourceSets[0].resources;
                    foreach (var item in resources)
                    {
                        if (item.address.countryRegion.Equals("Singapore"))
                        {
                            RequestData requestData = new RequestData();
                            requestData.addressString = item.address.formattedAddress.Split(',')[0];
                            requestData.state = item.address.adminDistrict;
                            requestData.city = item.address.adminDistrict2;
                            requestData.country = item.address.countryRegion;
                            requestData.latitude = item.geocodePoints[0].coordinates[0].ToString();
                            requestData.longitude = item.geocodePoints[0].coordinates[1].ToString();
                            requestData.LocationDisplay = item.address.formattedAddress.Split(',')[0];

                            if (!string.IsNullOrWhiteSpace(item.address.adminDistrict2))
                                requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict2;
                            if (!string.IsNullOrWhiteSpace(item.address.adminDistrict))
                                requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict;

                            if (location_lp.Items[0].Equals(loadingMsg))
                            {
                                location_lp.Items.Clear();
                            }

                            location_lp.Items.Add(requestData.LocationDisplay);
                            requestDataList.Add(requestData);
                        }
                    }
                }
            });
        }

        private void map_btn_Click(object sender, RoutedEventArgs e)
        {
            if (location_lp.Items.Count > 0)
            {
                RequestData requestData = requestDataList[location_lp.SelectedIndex];
                location_autocomplete.Text = requestData.addressString.Split(',')[0];

                if (!string.IsNullOrWhiteSpace(requestData.city))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.city;
                if (!string.IsNullOrWhiteSpace(requestData.state))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.state;
                if (!string.IsNullOrWhiteSpace(requestData.country))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.country;

                NavigationService.Navigate(new Uri("/ShowMap.xaml?location=" + location_autocomplete.Text + "&lat=" + requestData.latitude + "&lng=" + requestData.longitude, UriKind.Relative));
            }
        }

        private void location_lp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            location_autocomplete.Text = location_lp.SelectedItem.ToString();
        }

    }

    public class Point
    {
        public List<double> coordinates { get; set; }
    }

    public class GeocodePoint
    {
        [JsonProperty("type")]
        public string type { get; set; }

        [JsonProperty("coordinates")]
        public double[] coordinates { get; set; }

        [JsonProperty("calculationMethod")]
        public string calculationMethod { get; set; }

        [JsonProperty("usageTypes")]
        public string[] usageTypes { get; set; }
    }

    public class Address
    {
        public string adminDistrict { get; set; }
        public string adminDistrict2 { get; set; }
        public string countryRegion { get; set; }
        public string formattedAddress { get; set; }
        public string locality { get; set; }
    }

    public class Resource
    {
        public Point point { get; set; }
        public Address address { get; set; }
        public List<GeocodePoint> geocodePoints { get; set; }
    }

    public class ResourceSet
    {
        public List<Resource> resources { get; set; }
    }

    public class RootObject
    {
        public List<ResourceSet> resourceSets { get; set; }
    }

    public class RequestData
    {
        public string LocationDisplay { get; set; }
        public string latitude { get; set; }
        public string longitude { get; set; }
        public string addressString { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string country { get; set; }
    }
}